import router from "../router";
import axios from "axios";
import { Message } from "element-ui";
import { setTimeout } from "core-js";

/* let baseURL;
if (process.env.NODE_ENV === 'development') {
    console.log('开发环境')
    // baseURL = "http://localhost:8080";
    baseURL = "http://"+window.location.host;
} else if(process.env.NODE_ENV === 'production') {
    console.log('线上环境')
    baseURL = "http://"+window.location.host;
} */


let baseURL = window.location.protocol + '//' + window.location.host;

//只是为了本次演示，以后删除
// let baseURL = 'http://ydts3.hbwlife.com';

const instance = axios.create({
  headers: {
    "Content-Type": "application/json;charset=utf8"
  },
  baseURL: baseURL,
  timeout: 3000000,
  withCredentials: false
});


// 添加请求拦截器
instance.interceptors.request.use(
  config => {
    var username = localStorage.getItem("username");
    var token = localStorage.getItem("token");
    if (username && token) {
      config.headers["AUTH-TOKEN"] = username + "|" + token;
    //   config.headers["AUTH-TOKEN"] = "dasgasdgadgg";
    }
    return config;
  },
  error => {}
);

// 添加响应拦截器
instance.interceptors.response.use(
  response => {
    //console.log(response)
    // 对响应数据做些事
    if (response.status === 200) {
      if (response.data && response.data.code === 0) {
        return response; // 在请求成功后可以对返回的数据进行处理，再返回到前台
      } else if (response.data && response.data.code === -56055) {
          Message.error("登录已过期,请重新登录！");
          if (window.mysocket) {
              window.reStartStatus = false;
              if(window.timerWs){
                clearInterval(window.timerWs)
              }
              window.mysocket.close();
          }
          setTimeout(() => {
            router.push({ path: "/login" });
          },3000)
        return response;
      } else {
        //window.console.log(response.data);
      }
    }
    return response;
  },
  error => {
    //router.push("/login");
    //  console.log(error.response.data);
    return Promise.reject(error.response.data); // 返回接口返回的错误信息
  }
);

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function getData(url, data) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, {
        params: data
      })
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} data [请求时携带的参数]
 * @param {Object} config 配置参数
 */
export function postData(url, data, config) {
  return new Promise((resolve, reject) => {
    instance
      .post(url, data, config)
      .then(res => {
        // console.log(res.data);
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}
